
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include "Socket-Server.h"

//#include <arpa/inet.h>

int32_t CreaConexionServer_INET(char *puerto){

		int32_t Sock;
		int32_t yes =1;
		struct sockaddr_in direccion;
		memset(&direccion, 0, sizeof(struct sockaddr_in));

		if((Sock = socket(AF_INET, SOCK_STREAM, 0))== -1 )
		{
			printf ("error SOCKET");
		}
		direccion.sin_family= AF_INET;
		direccion.sin_addr.s_addr = INADDR_ANY;
		direccion.sin_port = htons( atoi(puerto));
		if(setsockopt(Sock, SOL_SOCKET , SO_REUSEADDR , &yes ,sizeof(yes))==-1){
			perror("setsockopt");
			close(Sock);
			exit(1);
		}
		if(bind(Sock,(struct sockaddr*) &direccion,  sizeof(direccion))==-1)
		{
			printf ("error BIND");

		}
		listen(Sock,1);

		return Sock;

}



int32_t CreaConexionServer_UNIX(void *pachUNIX){
	int32_t Sock;
	int32_t yes;
	yes =1;
	struct sockaddr_un  direccion;
	memset(&direccion, 0, sizeof(struct sockaddr_un));
	direccion.sun_family= AF_UNIX;
	strncpy(direccion.sun_path, pachUNIX, strlen(pachUNIX));

	if((Sock = socket(AF_UNIX, SOCK_STREAM,0))== -1 )
		{
		perror("error SOCKET");
		}
	if(setsockopt(Sock, SOL_SOCKET , SO_REUSEADDR, &yes ,sizeof(yes))==-1){
		perror("setsockopt");
		close(Sock);
		return -1;
	}
	unlink(direccion.sun_path);

	if(bind(Sock,(struct sockaddr *) &direccion, strlen (direccion.sun_path) + sizeof (direccion.sun_family))==-1)
	{
		perror("socketUnix:");
		close(Sock);
		return -1;
	}
	if(listen(Sock,1)==-1){
		printf("error en Listen\n");
		return -1;
	}

	return Sock;
}

void list_sockets_add(list_sockets * aList, int32_t aDescriptor)
{
	nodo_socket * aux;
	aux = (nodo_socket *)calloc(1, sizeof(nodo_socket));
	aux->descriptor = aDescriptor;
	aux->nxt = aList->list;
	aList->list = aux;
}

int32_t list_sockets_exists(list_sockets * aList, int32_t descriptor) //-1 si no existe 0 si existe
{
	nodo_socket * aux = aList->list;
	while(aux != NULL && aux->descriptor != descriptor)
		aux = aux->nxt;
	if(aux != NULL)
		return 0;
	else
		return -1;
}
